#include "../include/head.h"
#include "../include/func.h"

int splitString(const char * pstrs, const char* delimiter, char *tokens[], int max_tokens, int * pcount) {
    int token_count = 0;
    char *token = strtok((char *)pstrs, delimiter); // 使用delimiter作为分隔符

    while (token != NULL && token_count < max_tokens - 1) { // 保留一个位置给NULL终止符
        char * pstr = (char*)calloc(1, strlen(token) + 1);
        strcpy(pstr, token);
        tokens[token_count] = pstr;//保存申请的堆空间首地址
        token_count++;
        token = strtok(NULL, delimiter); // 继续获取下一个token
    }
    // 添加NULL终止符
    tokens[token_count] = NULL;
    *pcount= token_count;
    return 0;
}

int freeStrs(char * pstrs[], int count)
{
    for(int i = 0; i < count; ++i) {
        free(pstrs[i]);
    }
    return 0;
}

int parseCommand(const char* buff, int len, train_t* pt, User_t* user){
    //填写train内的User结构体
    pt->user.id = user->id;
    printf("username: %s\n", user->userName);
    strcpy(pt->user.userName,user->userName);
    strcpy(pt->user.salt,user->salt);
    strcpy(pt->user.cryptpasswd,user->cryptpasswd);
    strcpy(pt->user.pwd,user->pwd);

    //把buff里的第一个命令分词，然后判断CmdTpe的类型,填入train_t中
    char* tokens[64]; //token字符数组
    int max_tockens = 10; //最大分词数
    int pcount; //分词后参数个数
    char delimiter[8] = " "; //分隔符

    //分词
    splitString(buff, delimiter, tokens, max_tockens, &pcount);

    //添加对应命令类型
    if(strcmp(tokens[0], "pwd") == 0){
        pt->type = CMD_TYPE_PWD;
    }else if(strcmp(tokens[0], "ls") == 0){
        pt->type = CMD_TYPE_LS;
    }else if(strcmp(tokens[0], "cd") == 0){
        pt->type = CMD_TYPE_CD;
    }else if(strcmp(tokens[0], "mkdir") == 0){
        pt->type = CMD_TYPE_MKDIR;
    }else if(strcmp(tokens[0], "rmdir") == 0){
        pt->type = CMD_TYPE_RMDIR;
    }else if(strcmp(tokens[0], "puts") == 0){
        pt->type = CMD_TYPE_PUTS;
    }else if(strcmp(tokens[0], "gets") == 0){
        pt->type = CMD_TYPE_GETS;
    }else if(strcmp(tokens[0],"rm")==0){
        pt->type=CMD_TYPE_REMOVE;
    }
    else{
        pt->type = CMD_TYPE_NOTCMD;
    }

    //存入参数和辅助数据长度
    for(int i = 1; i < pcount; i++)
    {
        strcat(tokens[i], " ");
        strcat(pt->buff, tokens[i]);
    }

    //存入发送的参数的数据的长度
    pt->len = strlen(pt->buff);

    //释放tokens空间
    freeStrs(tokens, pcount);
    return 0;
}

